package com.my.house.controller;


import com.my.house.common.ApiResult;
import com.my.house.common.utils.ThreadLocalHolder;
import com.my.house.domain.Contract;
import com.my.house.domain.User;
import com.my.house.service.ContractService;
import com.my.house.vo.ContractReqVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 租房合同表 前端控制器
 * </p>
 *
 * @author yangll
 * @since 2025-02-08
 */
@Slf4j
@RestController
@RequestMapping("/api/contract")
public class ContractController {
    private final ContractService contractService;

    public ContractController(ContractService contractService) {
        this.contractService = contractService;
    }

    @GetMapping("/find-by-id")
    public ApiResult<Contract> findById(Long id) {
        log.info("/contract/find-by-id, id={}", id);
        User user = ThreadLocalHolder.getUser();
        assert user != null;
        return ApiResult.ok(contractService.findById(user.getId(), id));
    }

    @GetMapping("/find-by-room-id")
    public ApiResult<Contract> findByRoomId(Long roomId) {
        log.info("/contract/find-by-room-id, roomId={}", roomId);
        User user = ThreadLocalHolder.getUser();
        assert user != null;
        Assert.notNull(roomId, "房间ID不能为空");
        return ApiResult.ok(contractService.findEffectiveContractByRoomId(user.getId(), roomId));
    }

    @PostMapping("/add")
    public ApiResult<Void> addContract(@RequestBody @Validated ContractReqVO reqVO) {
        log.info("/contract/add, reqVO={}", reqVO);
        User user = ThreadLocalHolder.getUser();
        assert user != null;
        contractService.addContract(
                user.getId(),
                reqVO.getRoomId(),
                reqVO.getStartDate(),
                reqVO.getEndDate(),
                reqVO.getPrice(),
                reqVO.getLessee(),
                reqVO.getLesseeMobile(),
                reqVO.getLesseeNo(),
                reqVO.getDeposit(),
                reqVO.getRemark()
        );
        return ApiResult.ok();
    }

    @PostMapping("/checkout")
    public ApiResult<Void> checkout(@RequestBody Long roomId) {
        log.info("/contract/checkout, roomId={}", roomId);
        User user = ThreadLocalHolder.getUser();
        assert user != null;
        Assert.notNull(roomId, "房间ID不能为空");
        contractService.checkout(user.getId(), roomId);
        return ApiResult.ok();
    }
}
